import { Typeing } from '@/utils'
import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  HttpException,
  UnprocessableEntityException,
} from '@nestjs/common'
import { HttpStatus } from '@nestjs/common/enums'
import { Prisma } from '@prisma/client'
import { Response } from 'express'
import { prismaErrorCode } from '../errorCode/prismaCode'

@Catch(HttpException)
export class ValidateExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<Response>()
    const request = ctx.getRequest<Request>()
    // 常规错误处理
    if (exception instanceof BadRequestException) {
      const responseObject = exception.getResponse() as any
      return response.status(HttpStatus.UNPROCESSABLE_ENTITY).json({
        success: false,
        statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        message:
          Typeing(responseObject.message) === 'arry'
            ? responseObject.message.map((error) => {
                const info = error.split('-')
                if (info.length > 1) {
                  return {
                    file: info[0],
                    message: info[1],
                  }
                } else {
                  return {
                    message: info[0],
                  }
                }
              })
            : responseObject.message,
        path: request.url,
      })
      // 数据库错误 exception.getResponse()
    } 
    // 处理数据库抛出错误处理
    else if (exception instanceof UnprocessableEntityException) {
      const errorData = exception.getResponse() as any
      return response.status(exception.getStatus()).json({
        success: false,
        message: new prismaErrorCode(errorData).message,
        RawData: errorData,
      })
    } else {
      return response.status(exception.getStatus()).json(exception.getResponse())
    }
  }
}
